{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "              日期        证券号        开盘价        最高价        最低价        收盘价  \\\n",
      "0     2017-01-03  sh.000001  3105.3080  3136.4550  3105.3080  3135.9200   \n",
      "1     2017-01-04  sh.000001  3133.7870  3160.1020  3130.1140  3158.7940   \n",
      "2     2017-01-05  sh.000001  3157.9060  3168.5020  3154.2810  3165.4100   \n",
      "3     2017-01-06  sh.000001  3163.7760  3172.0340  3153.0250  3154.3210   \n",
      "4     2017-01-09  sh.000001  3148.5310  3173.1360  3147.7350  3171.2360   \n",
      "...          ...        ...        ...        ...        ...        ...   \n",
      "1087  2021-06-24  sh.000001  3568.5758  3570.4874  3548.8161  3566.6539   \n",
      "1088  2021-06-25  sh.000001  3567.3772  3614.2981  3564.5199  3607.5618   \n",
      "1089  2021-06-28  sh.000001  3612.2469  3614.3574  3594.2174  3606.3722   \n",
      "1090  2021-06-29  sh.000001  3601.6772  3601.8265  3570.5253  3573.1779   \n",
      "1091  2021-06-30  sh.000001  3572.6236  3594.1185  3569.5010  3591.1970   \n",
      "\n",
      "          昨日收盘价      成交数量(股)            成交金额(元)        涨跌幅  \n",
      "0     3103.6370  14156718592  159887138816.0000   1.040200  \n",
      "1     3135.9200  16786085120  195914293248.0000   0.729400  \n",
      "2     3158.7940  17472764416  199692025856.0000   0.209400  \n",
      "3     3165.4100  18370896640  207296036864.0000  -0.350300  \n",
      "4     3154.3210  17171407616  192110579712.0000   0.536200  \n",
      "...         ...          ...                ...        ...  \n",
      "1087  3566.2199  33544075400  461273595569.7000   0.012170  \n",
      "1088  3566.6539  34608783200  483898970868.6000   1.146955  \n",
      "1089  3607.5618  32127497400  456029594401.3000  -0.032975  \n",
      "1090  3606.3722  30607117800  440898705225.1000  -0.920435  \n",
      "1091  3573.1779  26816281800  414698378933.5000   0.504288  \n",
      "\n",
      "[1092 rows x 10 columns]\n",
      "logout success!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<baostock.data.resultset.ResultData at 0x1864603cb80>"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "##历史K线指标\n",
    "import baostock as bs  ##调用baostock库\n",
    "import pandas as pd    ##调用pandas库\n",
    "# 登陆系统\n",
    "lg = bs.login()\n",
    "# 周月线指标：date,code,open,high,low,close,volume,amount,adjustflag,turn,pctChg\n",
    "#code：股票代码，sh或sz.+6位数字代码\n",
    "rs = bs.query_history_k_data_plus(\"sh.000001\",\n",
    "    \"date,code,open,high,low,close,preclose,volume,amount,pctChg\",##以半角逗号分隔。此参数不可为空；\n",
    "    start_date='2017-01-01', end_date='2021-06-30', frequency=\"d\")##查询的起始日\n",
    "##frequency：数据类型，默认为d，日k线；d=日k线、w=周、m=月、5=5分钟、15=15分钟、30=30分钟、60=60分钟k线数据\n",
    "# 设定一个空集\n",
    "data_list = []\n",
    "while (rs.error_code == '0') & rs.next():##rs.error_code：当为“0”时表示连接成功，当为非0时表示失败；next()返回下一个项目\n",
    "    # 获取一条记录，将记录合并在一起\n",
    "    data_list.append(rs.get_row_data())#当以上的条件成立时，将数据放到空集中\n",
    "result = pd.DataFrame(data_list, columns=rs.fields)##导入pandas中\n",
    "result.rename(columns={'date':'日期'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'code':'证券号'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'open':'开盘价'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'high':'最高价'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'low':'最低价'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'close':'收盘价'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'preclose':'昨日收盘价'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'volume':'成交数量(股)'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'amount':'成交金额(元)'},inplace=True) #将表头的名称改成统一的名称\n",
    "result.rename(columns={'pctChg':'涨跌幅'},inplace=True) #将表头的名称改成统一的名称\n",
    "result[\"成交金额(元)\"].astype(float)\n",
    "\n",
    "# 输出到excel文件\n",
    "with pd.ExcelWriter(\"d:\\历史K线指标.xlsx\", mode='a',engine='openpyxl') as writer:\n",
    "    result.to_excel(writer,index=False)  \n",
    "print(result)\n",
    "\n",
    "# 登出系统\n",
    "bs.logout()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "| 函数名称 |\t作用 |\n",
    "| :--- | :---- |\n",
    "| query_history_k_data_plus()\t| 获取沪深A股估值指标(日频)数据（指数未提供估值数据）|\n",
    "| query_dividend_data()\t| 获取除权除息信息数据（预披露、预案、正式都已通过）| \n",
    "| query_adjust_factor()| \t获取复权因子信息数据| \n",
    "| query_profit_data()\t| 获取季频盈利能力信息| \n",
    "| query_operation_data()\t| 获取季频营运能力信息| \n",
    "| query_growth_data()\t| 获取季频成长能力信息| \n",
    "| query_balance_data()\t| 获取季频偿债能力信息| \n",
    "| query_cash_flow_data()\t| 获取季频现金流量信息| \n",
    "| query_dupont_data()\t| 获取季频杜邦指数信息| \n",
    "| query_performance_express_report()\t| 获取季频公司业绩快报信息| \n",
    "| query_stock_basic()\t| 获取证券基本资料| \n",
    "| query_stock_industry()\t| 获取行业分类信息| \n",
    "| query_sz50_stocks()\t| 获取上证50成分股信息，更新频率：每周一更新。| \n",
    "| query_hs300_stocks()\t| 获取沪深300成分股信息，更新频率：每周一更新。| \n",
    "| query_zz500_stocks()\t| 获取中证500成分股信息，更新频率：每周一更新。| \n",
    "| query_deposit_rate_data()\t| 获取存款利率| \n",
    "| query_loan_rate_data()\t| 获取贷款利率| \n",
    "| query_required_reserve_ratio_data()\t| 获取存款准备金率| \n",
    "| query_money_supply_data_month()\t| 获取货币供应量| \n",
    "| query_shibor_data()\t| 获取银行间同业拆放利率| \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "##导出当日所有的股票代码\n",
    "import pandas as pd\n",
    "import baostock as bs\n",
    "\n",
    "# 登陆系统\n",
    "lg = bs.login()\n",
    "# 显示登陆返回信息\n",
    "print('login respond error_code:' + lg.error_code)\n",
    "print('login respond error_msg:' + lg.error_msg)\n",
    "# 获取某一天的全市场的证券和指数代码\n",
    "rs = bs.query_all_stock(day=\"2018-06-28\")\n",
    "print('query_all_stock respond error_code:' + rs.error_code)\n",
    "print('query_all_stock respond error_msg:' + rs.error_msg)\n",
    "# 打印结果集\n",
    "code_list = []\n",
    "while (rs.error_code == '0') & rs.next():\n",
    " # 获取一条记录，将记录合并在一起\n",
    "    code_list.append(rs.get_row_data()[0])\n",
    "print(code_list)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "login respond error_code:0\n",
      "login respond error_msg:success\n",
      "logout success!\n",
      "        code code_name     ipoDate outDate type status\n",
      "0  sz.000858       五粮液  1998-04-27            1      1\n"
     ]
    }
   ],
   "source": [
    "##获取某只股票的信息\n",
    "import pandas as pd\n",
    "import baostock as bs\n",
    "\n",
    "# 登陆系统\n",
    "lg = bs.login()\n",
    "# 显示登陆返回信息\n",
    "print('login respond error_code:' + lg.error_code)\n",
    "print('login respond error_msg:' + lg.error_msg)\n",
    "rs = bs.query_stock_basic(code_name=\"五粮\")  # 支持模糊查询\n",
    "\n",
    "data_list = []\n",
    "while (rs.error_code == '0') & rs.next():\n",
    "        # 获取一条记录，将记录合并在一起\n",
    "        data_list.append(rs.get_row_data())\n",
    "result = pd.DataFrame(data_list, columns=rs.fields)\n",
    "bs.logout()\n",
    "print(result)\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "logout success!\n",
      "    calendar_date is_trading_day\n",
      "0      2020-01-01              0\n",
      "1      2020-01-02              1\n",
      "2      2020-01-03              1\n",
      "3      2020-01-04              0\n",
      "4      2020-01-05              0\n",
      "..            ...            ...\n",
      "361    2020-12-27              0\n",
      "362    2020-12-28              1\n",
      "363    2020-12-29              1\n",
      "364    2020-12-30              1\n",
      "365    2020-12-31              1\n",
      "\n",
      "[366 rows x 2 columns]\n"
     ]
    }
   ],
   "source": [
    "##导出有股市交易的日期,当值为0时，属于交易日，为1时，休息\n",
    "import pandas as pd\n",
    "import baostock as bs\n",
    "bs.login()\n",
    "data_list = []\n",
    "A=\"2020-01-01\"\n",
    "B=\"2020-12-31\"\n",
    "rs = bs.query_trade_dates(start_date=A, end_date=B)\n",
    "while (rs.error_code == '0') & rs.next():\n",
    "    data_list.append(rs.get_row_data())\n",
    "result = pd.DataFrame(data_list, columns=rs.fields)\n",
    "bs.logout()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "login success!\n",
      "请输入股票代码，如茅台为:sh.600519sh.600000\n",
      "login respond error_code:0\n",
      "login respond  error_msg:success\n",
      "query_performance_express_report respond error_code:0\n",
      "query_performance_express_report respond  error_msg:success\n",
      "        code performanceExpPubDate performanceExpStatDate  \\\n",
      "0  sh.600000            2020-01-22             2019-12-31   \n",
      "1  sh.600000            2021-01-28             2020-12-31   \n",
      "\n",
      "  performanceExpUpdateDate performanceExpressTotalAsset  \\\n",
      "0               2020-01-22         7004796000000.000000   \n",
      "1               2021-01-28         7959251000000.000000   \n",
      "\n",
      "  performanceExpressNetAsset performanceExpressEPSChgPct  \\\n",
      "0        493809000000.000000                    0.054054   \n",
      "1        638196000000.000000                   -0.035897   \n",
      "\n",
      "  performanceExpressROEWa performanceExpressEPSDiluted  \\\n",
      "0               12.300000                     1.950000   \n",
      "1               10.810000                     1.880000   \n",
      "\n",
      "  performanceExpressGRYOY performanceExpressOPYOY  \n",
      "0                0.116016                0.069189  \n",
      "1                0.029803               -0.044773  \n",
      "logout success!\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<baostock.data.resultset.ResultData at 0x186463a5dc0>"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import baostock as bs\n",
    "import pandas as pd\n",
    "\n",
    "#### 登陆系统 ####\n",
    "lg = bs.login()\n",
    "# 显示登陆返回信息\n",
    "stocknum = input(\"请输入股票代码，如茅台为:sh.600519\")\n",
    "print('login respond error_code:'+lg.error_code)\n",
    "print('login respond  error_msg:'+lg.error_msg)\n",
    "\n",
    "#### 获取公司业绩快报 ####\n",
    "rs = bs.query_performance_express_report(stocknum , start_date=\"2020-01-01\", end_date=\"2021-03-31\")\n",
    "print('query_performance_express_report respond error_code:'+rs.error_code)\n",
    "print('query_performance_express_report respond  error_msg:'+rs.error_msg)\n",
    "\n",
    "result_list = []\n",
    "while (rs.error_code == '0') & rs.next():\n",
    "    result_list.append(rs.get_row_data())\n",
    "    # 获取一条记录，将记录合并在一起\n",
    "result = pd.DataFrame(result_list, columns=rs.fields)\n",
    "\n",
    "# 打印输出\n",
    "print(result)\n",
    "# 结果集输出到csv文件\n",
    "#result_profit.to_csv(\"D:\\\\profit_data.csv\", encoding=\"gbk\", index=False)\n",
    "\n",
    "# 登出系统\n",
    "bs.logout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
